import React from 'react';
import Title from 'Page/CommonComponents/Title';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import { Button, List, Checkbox } from 'antd-mobile';
import { generateUUID } from 'Utils';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import './index.scss';

class ExamDetail extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      userId: props.params.userId,
      examId: props.params.examId,
      num: parseInt(sessionStorage.getItem('questionNum'), 10),
      questionArr: [],
      curentChoice: [],
      answers: [],
      loading: false
    };
    this.renderChoice = ::this.renderChoice;
    this.handleSingle = ::this.handleSingle;
    this.handleMulti = ::this.handleMulti;
    this.getCurentAnswer = ::this.getCurentAnswer;
  }
  componentWillMount() {
    this.initQuestion();
  }
  /*
  *  获取当前题 选择过的选项[]
  * */
  getCurentAnswer() {
    /*
    *  direction是为了在下一步上一步后能够获取准确的题
    * */
    const { answers, questionArr, num } = this.state;
    if (answers.length > 0) {
      const itemAnswer = answers.filter(item => item.biaoti === questionArr[num - 1].id);
      if (itemAnswer.length > 0) {
        this.setState({
          curentChoice: itemAnswer[0].answer
        });
      } else {
        this.setState({
          curentChoice: []
        });
      }
    } else {
      this.setState({
        curentChoice: []
      });
    }
  }
  /*
  *  做过的题的选项[{'biaoti':0,answer: ['']}]
  * */
  getAnswers() {
    const { questionArr, curentChoice, num } = this.state;
    let newAnswers = this.state.answers;
    const questionItem = {
      biaoti: questionArr[num - 1].id,
      answer: curentChoice
    };
    if (newAnswers.length !== 0) {
      newAnswers = newAnswers.filter(item => item.biaoti !== questionArr[num - 1].id);
    }
    newAnswers.push(questionItem);
    return newAnswers;
  }
  initQuestion() {
    const api = new Api({
      method: 'GET',
      path: `/choices/user/${this.state.examId}`,
      success: ((json) => {
        this.setState({
          questionArr: json
        });
      }),
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  handleChoiceChange(choice, question) {
    if (question.question_type === '单选题') {
      this.handleSingle(choice);
    } else if (question.question_type === '多选题') {
      this.handleMulti(choice);
    }
  }
  handleSingle(choice) {
    const newChoice = this.state.curentChoice;
    if (newChoice.length === 0) {
      newChoice.push(choice);
    } else if (newChoice[0] === choice) {
      newChoice.pop();
    } else {
      newChoice.pop();
      newChoice.push(choice)
    }
    this.setState({
      curentChoice: [...newChoice]
    });
  }
  handleMulti(choice) {
    let newChoice = this.state.curentChoice;
    if (newChoice.length === 0) {
      newChoice.push(choice);
    } else if (newChoice.indexOf(choice) > -1) {
      newChoice = newChoice.filter(item => item !== choice)
    } else {
      newChoice.push(choice)
    }
    this.setState({
      curentChoice: [...newChoice]
    });
  }
  handleNext() {
    const newNum = this.state.num;
    this.setState({
      num: newNum + 1,
      answers: this.getAnswers()
    }, () => {
      this.getCurentAnswer();
    })
  }
  handlePrev() {
    const newNum = this.state.num;
    this.setState({
      num: newNum - 1,
      answers: this.getAnswers()
    }, () => {
      this.getCurentAnswer();
    })
  }
  handleComplate() {
    const { answers, questionArr, num, curentChoice, userId, examId } = this.state;
    /*
    *  完成的时候需要将最后一题选项push到answers，
    *  其他题的push是在下一步的时候添加的
    * */
    const questionItem = {
      biaoti: questionArr[num - 1].id,
      answer: curentChoice
    };
    const newAnswers = answers.filter(item => item.biaoti !== questionArr[num - 1].id);
    newAnswers.push(questionItem);

    this.setState({ loading: true });

    const self = this;

    const api = new Api({
      method: 'POST',
      path: '/results/user',
      query: {
        tester_id: userId,
        subject_id: examId
      },
      data: {
        answers: newAnswers
      },
      success: (res) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => { self.props.dispatch(routerActions.go(-2)) },
          },
        ];
        dialog.open('提示', `您本次测评得分${res.score}分`, buttons, 'center');
        this.setState({ loading: false });
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
        this.setState({ loading: false });
      }
    });
    api.run();
  }
  renderChoice() {
    const { questionArr, num, curentChoice } = this.state;
    const serialArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
    const nodeInfo = [];
    const options = questionArr[num - 1].all_option;
    for (let i = 0, len = options.length; i < len; i++) {
      nodeInfo.push((
        <div key={generateUUID()} className="exam-row">
          <Checkbox
            onChange={() => { this.handleChoiceChange(serialArr[i], questionArr[num - 1]) }}
            checked={curentChoice.indexOf(serialArr[i]) > -1}
          >
            <span
              className="option"
              onClick={() => { this.handleChoiceChange(serialArr[i], questionArr[num - 1]) }}
            >{`${serialArr[i]}、`}{options[i]}</span>
          </Checkbox>
        </div>
      ))
    }
    return nodeInfo;
  }
  render() {
    const { questionArr, num, loading } = this.state;
    return (
      <div className="exam-detail-page">
        <Title title="食安知识测评" />
        <div className="exam-content-wrap">
          <div className="exam">
            {
              questionArr.length > 0 ?
                <div className="exam-wrap">
                  <div className="exam-title">{`${num}、`}{`(${questionArr[num - 1].question_type})`}{questionArr[num - 1].question}</div>
                  <List>
                    {
                      this.renderChoice()
                    }
                  </List>
                </div>
                : ''
            }
          </div>
          <div className="btn">
            <Button
              disabled={num === 1}
              onClick={this.handlePrev.bind(this)}
            >
              上一题
            </Button>
            {
              num === questionArr.length ?
                <Button onClick={this.handleComplate.bind(this)} loading={loading}>完成</Button>
                :
                <Button
                  disabled={questionArr.length === 0}
                  onClick={this.handleNext.bind(this)}
                >下一题</Button>
            }
          </div>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(ExamDetail);
